import Vue from 'vue'
import VueRouter from 'vue-router'
// 1.导入路由
import login from '@/views/user/login.vue'
import home from '@/views/home/home.vue'
import qa from '@/views/qa/qa.vue'
import movie from '@/views/movie/movie.vue'
import user from '@/views/user/user.vue'
import layout from '@/views/layout.vue'
import notfound from '@/views/notfound/notfound.vue/'
import edit from '@/views/user/edit.vue'
import article from '@/views/home/article.vue'
import search from '@/views/home/search.vue'
import searchResult from '@/views/home/searchResult.vue'
import student from '@/views/user/student.vue'


Vue.use(VueRouter)

// 2.配置路由规则
const routes = [
  {
    name: 'login',
    path: '/login',
    component: login
  },
  {
    name: 'edit',
    path: '/edit',
    component: edit
  },
  {
    name: 'myarticle',
    path: '/article',
    component: article
  },
  {
    name: 'search',
    path: '/search',
    component: search
  },
  {
    name: 'searchResult',
    path: '/searchResult',
    component: searchResult
  },
  {
    name: 'student',
    path: '/student',
    component: student
  },
  {
    name: 'layout',
    path: '/',
    component: layout,
    children: [
      {
        name: 'home',
        path: '/home',
        component: home
      },
      {
        name: 'qa',
        path: '/qa',
        component: qa
      },
      {
        name: 'movie',
        path: '/movie',
        component: movie
      },
      {
        name: 'user',
        path: '/user',
        component: user,
        meta: {
          isLogin: true
        }
      },
      {
        path: '/',
        redirect: '/home'
      }
    ]
  },
  {
    name: 'notfound',
    path: '/notfound',
    component: notfound
  },
  {
    /* 
      (1)*路径通配符：任意路径重定向到notfound
      (2) 路由默认从上往下匹配的，如果可以匹配到则跳转页面。无法匹配则继续往下匹配知道所有路由器知道所有路由匹配结束
     */
    path: '*',
    redirect: '/notfound'
  }
]

/*  */
// 1. 先存储VueRouter的原生push方法
// const orginPush = VueRouter.prototype.push
// 2. 


const router = new VueRouter({
  routes
})

import { getToken } from '@/utils/token.js'
import { Toast } from 'vant'
/* 注册路由前置导航守卫 */
router.beforeEach((to, from, next) => {
  // to:去哪里 路由信息 (要跳转的路由)
  // console.log('to:', to)
  // from：从哪来 路由信息 (从哪个路由跳转)
  // console.log('from:', from)
  /*  next:***必须要调用的，否则路由无法跳转***
    next():没有传参。通过检查。允许跳转to页面
    next('/path'):传参数，没有通过验证，跳转到指定的页面
 */

  /* 并不是所有的页面都需要做登录判断，把需要登录判断的页面添加meta */
  // 1. 判断这个页面是否需要做登录判断
  if (to.meta.isLogin) {
    // 1.1 需要做登录判断
    // 2. 检查用户有没有token
    if (getToken()) {
      // 2.1 有登录，不拦截，允许正常跳转
      next()
    } else {
      // 2.2 没登录，进行拦截。跳转登录页
      // (1)弹窗提示
      Toast.fail('请登录')
      // (2)跳转登录页
      next('/login')
      // (3)清除浏览器爆红提示
      setTimeout(()=>{
        console.clear()
      },500)
    }
  } else {
    // 1.2 不需要做登录判断，无条件跳转
    next()
  }
})
export default router
